package main

import (
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

type User struct {
	gorm.Model
	Name string
	Age  int64
}

func main() {
	db, err := gorm.Open("mysql", "root:123456@(10.10.10.101:33306)/db1?charset=utf8&parseTime=True&loc=Local")
	if err != nil {
		panic(err)
	}
	defer db.Close()

	// 自动创建表  自动迁移 （把结构体和数据表进行映射）
	db.AutoMigrate(&User{})

	// 创建2条记录
	//u1 := User{Name: "大狗", Age: 20}
	//db.Create(&u1)
	//u2 := User{Name: "二狗", Age: 18}
	//db.Create(&u2)

	// 查询
	//var user User
	//db.First(&user) // 查询第一条记录，赋值给user结构体变量
	//fmt.Printf("%#v\n", user)

	//var users []User
	//db.Find(&users) // 查询所有数据
	//fmt.Printf("%#v\n", users)

	// 条件查询：
	// Get first matched record
	//var user User
	//db.Where("name = ?", "二狗").First(&user)
	// SELECT * FROM users WHERE name = '二狗' limit 1;

	// Get all matched records
	//var users []User
	//db.Where("name = ?", "二狗").Find(&users)
	// SELECT * FROM users WHERE name = '二狗';

	// <>
	//db.Where("name <> ?", "二狗").Find(&users)
	// SELECT * FROM users WHERE name <> '二狗';

	// IN
	//db.Where("name IN (?)", []string{"大狗", "二狗"}).Find(&users)
	// SELECT * FROM users WHERE name in ('二狗','二狗');

	// LIKE
	//db.Where("name LIKE ?", "%二%").Find(&users)
	// SELECT * FROM users WHERE name LIKE '%二%';

	// AND
	//db.Where("name = ? AND age >= ?", "jinzhu", "22").Find(&users)
	// SELECT * FROM users WHERE name = '二狗' AND age >= 18;

	// Time
	//db.Where("updated_at > ?", lastWeek).Find(&users)
	// SELECT * FROM users WHERE updated_at > '2000-01-01 00:00:00';

	// BETWEEN
	//db.Where("created_at BETWEEN ? AND ?", lastWeek, today).Find(&users)
	// SELECT * FROM users WHERE created_at BETWEEN '2000-01-01 00:00:00' AND '2000-01-08 00:00:00';

	// 更多查询操作参考： https://www.topgoer.cn/docs/gorm/gormchaxun
}
